from django.db import models

# Create your models here.
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager
from django.contrib.auth.models import Permission, Group
from django.contrib.auth.validators import ASCIIUsernameValidator, UnicodeUsernameValidator
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from utils import const

from base.models import BaseVmodel


class Role(BaseVmodel):
    """
    角色
    """
    name = models.CharField(verbose_name=u"角色名称", max_length=64, db_index=True)
    key = models.CharField(verbose_name=u"角色代码", max_length=64, db_index=True)
    description = models.CharField(verbose_name=u"描述", max_length=256, blank=True, null=True)

    class Meta(object):  # pylint: disable=C0111
        db_table = "t_role"
        verbose_name = verbose_name_plural = u"角色"

    def __str__(self):
        return self.name


class User(BaseVmodel, AbstractBaseUser, PermissionsMixin):
    """
    用户
    """
    username_validator = UnicodeUsernameValidator()
    password = models.CharField(max_length=128, verbose_name='password')
    last_login = models.DateTimeField(blank=True, null=True, verbose_name='上次登陆时间')
    is_superuser = models.BooleanField(default=False, help_text='指明该用户缺省拥有所有权限', verbose_name='超级用户')
    username = models.CharField(u"平台帐号", max_length=150, unique=True,
                                help_text=_("Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."),
                                validators=[username_validator],
                                error_messages={"unique": _("A user with that username already exists."), })
    name = models.CharField(max_length=64, blank=True, null=True, verbose_name=u'姓名')
    status = models.IntegerField(verbose_name="状态", choices=((0, "停用"), (1, "启用")), default=1)
    email = models.EmailField(blank=True, null=True, verbose_name=_('email address'))
    phone = models.CharField(verbose_name=u'手机号码', max_length=64, blank=True, null=True)
    sex = models.IntegerField(verbose_name=u'用户性别', default=2, choices=const.CONST_SEX.items())
    is_admin = models.IntegerField(verbose_name=u'是否管理员', default=0, choices=((0, "否"), (1, "是")))

    last_login_time = models.DateTimeField(blank=True, null=True, verbose_name=u'上次登陆时间')
    is_active = models.BooleanField(default=True, verbose_name=u"有效")
    is_staff = models.BooleanField(verbose_name="可以登录", default=True, help_text=_("指明该用户是否可以登录此系统"))
    date_joined = models.DateTimeField(_("date joined"), default=timezone.now)

    role = models.ForeignKey(Role, on_delete=models.CASCADE, blank=True, null=True, verbose_name='角色')

    objects = UserManager()

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ["email", ]

    class Meta(object):  # pylint: disable=C0111
        ordering = ("order",)
        db_table = "t_user"
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        permissions = [
            ("can_manage_books", "管理图书"),
            ("can_borrow_books", "借阅图书"),
        ]

    def __str__(self):
        return self.username if not self.name else self.name

    @property
    def role_key(self):
        key = None
        try:
            if self.role and self.role.key:
                key = self.role.key
        except (BaseException,):
            pass

        return key

    def get_info(self, include=None, exclude=None):
        exclude = ['password', 'del_flag', 'last_login_time', 'date_joined']
        info = super(User, self).get_info(exclude=exclude)
        info['role_key'] = self.role_key
        return info

    def get_name(self):
        return str(self.name or self.username)
